package com.mq.ps.topic;

import com.mq.config.ConnectUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

public class HelloWorldRec2 {

    private final static String EXCHANGE_NAME = "TOPIC_EXCHANGE_NAME";

    private final static String QUEUE_NAME = "TOPIC_CONSUMER_02";

    public static void recMsg() throws URISyntaxException, KeyManagementException, TimeoutException, NoSuchAlgorithmException, IOException {
        //1. 获取连接
        Connection connect = ConnectUtils.getConnect();
        //2. 获取信道
        Channel channel = connect.createChannel();
        //3. 声明队列
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);
        //4. 绑定路由
        String key ="INSERT.#";
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME, key);
        //5. 接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, StandardCharsets.UTF_8);
                System.out.println("[消费者2] 接收消息:"+msg);
            }
        };
        //6. 确认接收
        channel.basicConsume(QUEUE_NAME,true,consumer);
    }

    public static void main(String[] args) throws KeyManagementException, TimeoutException, NoSuchAlgorithmException, IOException, URISyntaxException {
        HelloWorldRec2.recMsg();
    }
}
